<template>
  <div v-loading="state.loading">
    <div class="opts">
      <ElSlider v-model="state.height" siz="small" :step="1" :min="0" :max="500" />
    </div>
    <div class="btns">
      <button class="btn" @click="analyse">分析</button>
      <button class="btn" @click="clean">清除</button>
    </div>
  </div>
</template>

<script setup>
  import { onBeforeUnmount, onMounted, reactive, watch } from 'vue';
  import * as Cesium from 'cesium';
  import useDraw, { DrawType } from '@/hooks/useDraw';
  import { ElNotification } from 'element-plus';
  import { vLoading, ElSlider } from 'element-plus';
  import { HeightRestrictionAnalysis } from 'cgak';

  const state = reactive({
    tiped: false,
    loading: false,
    height: 50,
    baseHeight: 0,
  });

  let analyser = new HeightRestrictionAnalysis(window.viewer, {
    height: state.height,
    baseHeight: state.baseHeight,
    upColor: '#0f0',
    downColor: '#f00',
    extrudedHeight: 1000,
  });

  const { drawStart, drawStop, drawClear } = useDraw(window.viewer, {
    type: DrawType.POLYGON,
    finishCallback: positions => {
      if (positions.length >= 3) {
        drawClear();
        analyser.analyse(positions);
        setTimeout(() => {
          analyser.changeUpHeight(state.height);
          state.loading = false;
        }, 1500);
      }
    },
  });

  const analyse = () => {
    if (!state.tiped) {
      ElNotification({ message: '点击鼠标左键绘制视线，每两点分析一次，点击右键结束。', duration: 5000 });
      state.tiped = true;
    }
    drawStart();
  };

  const clean = () => {
    drawStop();
    drawClear();
    analyser?.clear();
  };

  watch(
    () => state.height,
    () => {
      analyser.changeUpHeight(state.height);
    }
  );

  onBeforeUnmount(() => {
    clean();
  });
</script>
